package com.ainiyar.springweb.config.security.handler;

import com.ainiyar.springweb.common.exception.CustomExceptionAdvice;
import com.ainiyar.springweb.common.exception.CustomerAuthenticationException;
import com.ainiyar.springweb.common.result.ResultResponse;
import com.ainiyar.springweb.util.WebUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**************************************
 * File Name : LoginFailureHandler
 * Created with : IntelliJ IDEA.
 * Author : 艾尼亚尔·毛拉吾提
 * QQ : 524155792  WeChat : ainiyar0124
 * Created Time : 2024/2/5  00:26
 * Desc :登录失败处理类
 ***************************************/
@Component
public class LoginFailureHandler implements AuthenticationFailureHandler {
    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        //设置响应编码格式
        response.setContentType("application/json;charset=utf-8");
        //定义变量，保存异常信息
        String message = null;
        int code = 400;
        //判断异常类型
        if (exception instanceof AccountExpiredException) {
            message = "账号过期、登录失败！";
        } else if (exception instanceof BadCredentialsException) {
            message = "账号或密码错误、登录失败！";
        } else if (exception instanceof CredentialsExpiredException) {
            message = "密码过期、登录失败！";
        } else if (exception instanceof DisabledException) {
            message = "账号禁用、登录失败！";
        } else if (exception instanceof LockedException) {
            message = "账号被锁定 、登录失败！";
        } else if (exception instanceof InternalAuthenticationServiceException) {
            message = exception.getMessage();
        } else if (exception instanceof CustomerAuthenticationException) {
            message = exception.getMessage();
            code = 600;
        }else if (exception instanceof CustomExceptionAdvice){
            message = exception.getMessage();
        }else {
            message = "登录失败！";
        }
        ResultResponse<Object> result=ResultResponse.Fail(message,code);
        WebUtil.renderString(response,result);
    }
}

